package www.superbytecode.com.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import www.superbytecode.com.enums.DBType;
import www.superbytecode.com.model.DatabaseAttribute;
import www.superbytecode.com.model.UITableColumn;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * All rights Reserved, Designed By www.super-bytecode.com
 *
 * @ProjectName superbytecode-builder
 * @Package www.superbytecode.com.util
 * @ClassName DbUtil
 * @Description
 * @Author [Lance Ting]
 * @Date 2020/7/14 20:37
 * @Version V1.0
 * @Copyright: 2020 www.super-bytecode.com Inc. All rights reserved.
 * @TODO：本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
public class DbUtil {

    private static final Logger logger = LoggerFactory.getLogger(DbUtil.class);
    private static final int DB_CONNECTION_TIMEOUTS_SECONDS = 1;

    public static Connection getConnection(DatabaseAttribute config) throws ClassNotFoundException, SQLException {
        DriverManager.setLoginTimeout(DB_CONNECTION_TIMEOUTS_SECONDS);
        DBType dbType = DBType.valueOf(config.getDbType());
        Class.forName(dbType.getDriverClass());
        String url = getConnectionUrlWithSchema(config);
        logger.info("getConnection, connection url: {}", url);
        return DriverManager.getConnection(url, config.getUsername(), config.getPassword());
    }

    public static List<String> getTableNames(DatabaseAttribute config) throws Exception {
        String url = getConnectionUrlWithSchema(config);
        logger.info("getTableNames, connection url: {}", url);
        Connection conn = DriverManager.getConnection(url, config.getUsername(), config.getPassword());
        DatabaseMetaData md = conn.getMetaData();
        ResultSet rs = md.getTables(null, config.getUsername().toUpperCase(), null, null);
        List<String> tables = new ArrayList<>();
        while (rs.next()) {
            tables.add(rs.getString(3));
        }
        return tables;
    }

    public static List<UITableColumn> getTableColumns(DatabaseAttribute dbConfig, String tableName) throws Exception {
        String url = getConnectionUrlWithSchema(dbConfig);
        logger.info("getTableColumns, connection url: {}", url);
        Connection conn = getConnection(dbConfig);
        DatabaseMetaData md = conn.getMetaData();
        ResultSet rs = md.getColumns(null, null, tableName, null);
        List<UITableColumn> columns = new ArrayList<>();
        while (rs.next()) {
            UITableColumn columnVO = new UITableColumn();
            String columnName = rs.getString("COLUMN_NAME");
            columnVO.setColumnName(columnName);
            columnVO.setJdbcType(rs.getString("TYPE_NAME"));
            columns.add(columnVO);
        }
        return columns;
    }

    public static String getConnectionUrlWithSchema(DatabaseAttribute dbConfig) throws ClassNotFoundException {
        DBType dbType = DBType.valueOf(dbConfig.getDbType());
        String connectionUrl = String.format(dbType.getConnectionUrlPattern(), dbConfig.getHost(), dbConfig.getPort(), dbConfig.getSchema(), dbConfig.getEncoding());
        logger.info("getConnectionUrlWithSchema, connection url: {}", connectionUrl);
        return connectionUrl;
    }

}